from typing import Any, List, Union
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

'''
1.1 response_model
'''
class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None
    tags: List[str] = []

@app.post("/items1/", response_model=Item)
async def create_item(item: Item) -> Any:
    return item

@app.get("/items2/", response_model=List[Item])
async def read_items() -> Any:
    return [
        {"name": "Portal Gun", "price": 42.0},
        {"name": "Plumbus", "price": 32.0},
    ]

'''
1.2 response_model_exclude_unset
'''
class Item1(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: float = 10.5
    tags: List[str] = []

items = {
    "foo": {"name": "Foo", "price": 50.2},
    "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
    "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}

@app.get("/items3/{item_id}", response_model=Item1, response_model_exclude_unset=True)
async def read_item(item_id: str):
    return items[item_id]

'''
1.3 response_model_include 和 response_model_exclude
'''
@app.get(
    "/items/{item_id}/name",
    response_model=Item1,
    response_model_include={"name", "description"}
)
async def read_item_name(item_id: str):
    return items[item_id]

@app.get("/items/{item_id}/public", response_model=Item1, response_model_exclude={"tax"})
async def read_item_public_data(item_id: str):
    return items[item_id]





if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)